#!/bin/bash

# 输出所有传入的参数
echo $1 $2 $3 $4 $5
build_mod=$2
version_file_path=""
version_content=""
line="============================="

# 定义发送消息到钉钉机器人的函数
send_to_dingtalk_robot(){
    if [ "$muteRobot"x != "true"x ]; then
        dingtalk_robot_url="https://oapi.dingtalk.com/robot/send?access_token=7dcd4e90934d3a6e9e3f5d34cf0ba91376daf413839e54c7dc180f6b7c82fcc5"
        curl $dingtalk_robot_url -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content":"[server_game]'"$1 $2 $3 $4 $5"'"}}'
        echo
    else
        echo $1 $2 $3 $4 $5
    fi
}

# 定义输出一行分隔线的函数
echo_line(){
    echo $line
}

# 定义输出内容到版本文件的函数
echo_to_version(){
    echo $1    
    if [ x$version_file_path != x"" ]
    then
         echo $1 >> $version_file_path
        version_content="$version_content\n$1"
    fi    
}

# 定义输出一行分隔线到版本文件的函数
echo_line_to_version(){
    echo_to_version $line
}

# 定义输出使用说明的函数
usage(){
    echo_line_to_version
    echo_to_version
    echo_to_version "usage:
    ./_build.sh debug|release [ outpath ]
    
    "
}

# 定义停止构建并发送失败消息到钉钉机器人的函数
stop_build(){
    echo_to_version
    echo_to_version "$service_name build failed!!!!"
    send_to_dingtalk_robot "$prjname build failed!\n$version_content"

    if [ ! -z "$release_parent_path" ]; then
        rm -rf $release_parent_path
    fi
    exit 128
}

# 定义构建服务的函数
build_service(){
    # service_name="firebase-msg-rpc"
    cd $root_path
    service_path="$root_path/$service_name"

    echo_to_version
    echo_to_version "start build $service_name"

    cd $service_name
    service_out_path="$release_path/$service_name"
    mkdir -p "$service_out_path/etc"
    cp -r $service_path/etc/* "$service_out_path/etc/"

    mkdir -p "$service_out_path"
    exefilename=$service_name
    if [ "$GOOS"x = "windows"x ]; then
        exefilename="$exefilename.exe"
    fi 

    CGO_ENABLED=0 go build -o "$service_out_path/$exefilename"
    if [ $? != 0 ]; then
        stop_build
    fi

    # build_result=`go build -o "$service_out_path/$exefilename"`
    # echo "buildresult:"$build_result
    # if [ ! -z "$build_result" ]; then
    #     # build 失败
    #     echo_to_version $build_result
    #     stop_build
    # fi

    cd $service_out_path
    yamlfiles=`ls etc/*.yaml`
    for yamlname in $yamlfiles
    do
        yamlname_shortname=$(basename ${yamlname} .yaml)
        # 根据配置文件创建运行的shell脚本
        start_shell_name="start.$yamlname_shortname.sh"
        touch $start_shell_name
        echo '#!/bin/bash' >> $start_shell_name
        echo 'start_time=`date +%Y%m%d%H%M%S`' >> $start_shell_name

        # docker 开头的配置文件，输出目录放到 /data/logs/ 中
        # if [ "$yamlname_shortname" = "docker"* ]; then
        if echo "$yamlname_shortname" | grep -q '^docker'; then
            echo "logfilename=/data/logs/$service_name.$yamlname_shortname.\$start_time.log" >> $start_shell_name
        else
            echo "logfilename=../log/$service_name.$yamlname_shortname.\$start_time.log" >> $start_shell_name
        fi

        # if [ "$yamlname_shortname" == "docker"* ]; then
        #     echo "is docker"
        # else
        #     echo "not docker"
        # fi        

        echo "echo \$logfilename" >> $start_shell_name
        # echo "./$exefilename -f ./$yamlname " >> $start_shell_name
        echo "nohup ./$exefilename -f ./$yamlname > \$logfilename &" >> $start_shell_name
        echo "sleep 1.0" >> $start_shell_name
        echo "tail -f \$logfilename" >> $start_shell_name
        chmod +x $start_shell_name
        echo_to_version "    - $start_shell_name"
    done
    
}

# 检查给定的字符串是否在字符串列表中的函数
check_str_in_strs(){
    target=$1
    strs=$2

    result_check_str_in_strs=0

    if [ -z "$target" ]; then
        return
    fi

    for str in $strs
    do
        if [ "$target"x = "$str"x ]; then
            result_check_str_in_strs=1
            return
        fi
    done
}

# 设置输出目录
out_path=$1 # 输出目录
if [ -z "$out_path" ]; then
    out_path="../out"
fi

# 设置构建模式  debug/release
build_mod=$2 # build 模式  debug/release
if [ -z "$build_mod" ]; then
    build_mod="debug"
fi

# 设置构建平台  arm64 amd64
build_arch=$3 # build平台  arm64 amd64
if [ ! -z "$build_arch" ]; then
    check_str_in_strs $build_arch "arm amd arm64 amd64"
    if [ $result_check_str_in_strs -ne 1 ] 
    then
        echo_to_version "Unknow arch: $build_arch"
        stop_build
    fi
    export GOARCH=$build_arch
else
    export GOARCH=`go env GOHOSTARCH`
fi

# 设置目标系统 windows linux darwin
build_os=$4 # 目标系统 windows linux darwin
if [ ! -z "$build_os" ]; then
    check_str_in_strs $build_os "windows linux darwin"
    if [ $result_check_str_in_strs -ne 1 ] 
    then
        echo_to_version "Unknow OS: $build_os"
        stop_build
    fi
    export GOOS=$build_os
else
    export GOOS=`go env GOHOSTOS`
fi

prjname="server_game" # 工程名称

# 生成版本号
version_code=`date +%Y%m%d%H%M%S`
version_file_name=version_$version_code

# 获取主机名和IP地址
myhostname=`hostname`
ips=`hostname -i`

# 构建开始消息
build_start_msg="$prjname ($build_mod) Starting: \n Host: $myhostname \n IP: $ips \n arch: $GOARCH \n system: $GOOS \n version: $version_file_name"
# echo $build_start_msg
send_to_dingtalk_robot "$build_start_msg"

# 读取需要构建的服务列表
all_service_name=`cat ../shell/service_list.txt`

# 获取当前工作目录
root_path=`pwd`

# 检查输出目录是否存在
if [ ! -d "$out_path" ]; then
    echo_to_version "Invalid out path: $out_path"
    usage
    stop_build
fi

# 设置输出目录的绝对路径
cd $out_path
out_path=`pwd`
cd $root_path
release_latest_path=""

# 根据构建模式设置发布路径
if [ "$build_mod"x = "debug"x ]; then
    release_parent_path="$out_path/debug/$GOARCH/$GOOS"
    release_path="$release_parent_path/$prjname"
    rm -rf $release_path
    mkdir -p $release_path
elif [ "$build_mod"x = "release"x ]; then
    release_parent_path=$out_path/release/$GOARCH/$GOOS/$prjname.$version_code
    release_path="$release_parent_path/$prjname"    
    release_latest_path="$out_path/release/latest/server_game"
    if [ -d "$release_path" ]; then
        echo "out path exist: $release_path"
        usage
        stop_build
    fi           
else
    echo "build mod err: $build_mod"
    usage
    stop_build
fi

# 创建日志目录
mkdir -p $release_path/log

# 拷贝公共配置文件和通用运行文件
cp -r a_config $release_path
cp -r common_run_service.sh $release_path

# 设置版本文件路径并创建版本文件
version_file_path="$release_path/$version_file_name.txt"
touch $version_file_path

# 设置版本号文件路径并创建版本号文件
version_code_file_path="$release_path/version_code"
touch $version_code_file_path
echo $version_code > $version_code_file_path

# 输出构建信息到版本文件
echo_line_to_version
echo_to_version "Build PC:\t$myhostname"
echo_to_version "IP List:\t$ips"
echo_to_version "Version:\t$version_code"
echo_to_version "Build mod:\t$build_mod"
echo_to_version "Build arch:\t$GOARCH"
echo_to_version "Build os:\t$GOOS"
echo_to_version "Out path:\t$release_path"
echo_to_version "Services:\t$all_service_name"

# 创建发布路径
echo_line_to_version
mkdir -p "$release_path"

# 循环构建每个服务
for s in $all_service_name
do
    service_name=$s
    build_service
done

# 更新最新的发布路径
if [ "$release_latest_path"x != ""x ]; then
    mkdir -p $release_latest_path
    rm -rf $release_latest_path/*
    cp -rf $release_path/* $release_latest_path/
fi

# 输出构建完成信息到版本文件
echo_to_version
echo_line_to_version
echo_to_version
echo_to_version "build complete!!!"
echo_to_version

# 发送构建完成消息到钉钉机器人
# version_content=`cat $version_file_path`
send_to_dingtalk_robot "$prjname Build complete!\n$version_content"
if [ "$isLocalBuild"x != "false"x ]; then
    open $release_path
fi